package com.whl.cloud.oauth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.whl.cloud.fergn.UserCenter;
import com.whl.cloud.model.UserInfoResult;

@Component
public class UserDetailsServiceImpl implements UserDetailsService{

	@Autowired
	UserCenter userCenter;
	@Autowired
	PermissionServiceImpl permissionService;
	
	@Transactional
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfoResult userInfoResult = userCenter.loadUserByAccount(username);
		Assert.notNull(userInfoResult, "找不到账号密码");
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		// 获取用户的授权
		List<String> permissions = userCenter.findByUserId(userInfoResult.getId());
		// 声明授权文件
		for (String permission : permissions) {
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission);
			grantedAuthorities.add(grantedAuthority);
		}
		return new User(userInfoResult.getId().toString(), userInfoResult.getId().toString(), grantedAuthorities);
	}

}
